package uit.shoeshop.dao;

import uit.shoeshop.dto.CategoryDTO;
import uit.shoeshop.dto.InformationDTO;
import uit.shoeshop.lib.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class InformationDAO {
	private Connection conn;
	private String tableName;
	
	public InformationDAO(){
		setConn(null);
		setTableName(Constants.TBL_INFORMATION);
	}
	
	public InformationDTO getInformationByCode(String pageCode) throws SQLException{
		InformationDTO result = new InformationDTO();
		try{
			setConn(Util.Connect());
			String sql = "SELECT * FROM " + getTableName() + " WHERE page_code = ?";
			PreparedStatement stm = getConn().prepareStatement(sql);
			
			//gan gia tri cho cau sql
			stm.setString(1, pageCode);

			
			//thuc hien cau lenh sql
			ResultSet rs = stm.executeQuery();
			
			while (rs.next()) {
				result.setContent(rs.getString("content"));
				result.setInformation_id(rs.getInt("information_id"));
				result.setPage_code(rs.getString("page_code"));
				result.setTitle(rs.getString("title"));
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(getConn() != null)
				getConn().close();
		}		
		return result;
	}
	
	public int updateInformationByCode(String pageCode,String title,String content) throws SQLException{
		int result = 1;
		try{
			InformationDTO check = this.getInformationByCode(pageCode);
			setConn(Util.Connect());
			String sql = "";
			if(check != null){
				sql = "UPDATE "+getTableName()+" SET title=?,content=? WHERE page_code=?";
			}else{
				sql = "INSERT INTO "+getTableName()+" (page_code,title,content) VALUES (?,?,?)";				
			}
			PreparedStatement stm = getConn().prepareStatement(sql);
			
			//gan gia tri cho cau sql
			stm.setString(1, title);
			stm.setString(2, content);
			stm.setString(3, pageCode);			

			if(stm.executeUpdate() < 1)
				throw new Exception("Khong update hay insert duoc !");
		}catch(Exception e){
			e.printStackTrace();
			result=0;
		}finally{
			if(getConn() != null)
				getConn().close();
		}		
		return result;
	}	
	/**
	 * @param conn the conn to set
	 */
	public void setConn(Connection conn) {
		this.conn = conn;
	}

	/**
	 * @return the conn
	 */
	public Connection getConn() {
		return conn;
	}

	/**
	 * @param tableName the tableName to set
	 */
	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	/**
	 * @return the tableName
	 */
	public String getTableName() {
		return tableName;
	}
	
}
